package com.gjy.sentinel.demo.flow;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-10-15 15:57:32
 */
public class FlowDemo {
    private static final Logger log = LoggerFactory.getLogger(FlowDemo.class);
    private static final String RESOURCE = "HelloService";

    public void initFlow() {
        ArrayList<FlowRule> rules = new ArrayList<>();
        FlowRule fr1 = new FlowRule();
        fr1.setResource(RESOURCE);
        fr1.setCount(5);
        fr1.setGrade(RuleConstant.FLOW_GRADE_THREAD);
        rules.add(fr1);
        FlowRuleManager.loadRules(rules);
    }

    /**
     * 调用一次限流入口，返回 true 表示通过，false 表示被阻塞
     */
    public boolean tryAccess() {
        Entry entry = null;
        try {
            entry = SphU.entry(RESOURCE);
            log.info("OK");
            return true;
        } catch (BlockException e) {
            log.error("FALSE");
            Tracer.trace(e);
            return false;
        } finally {
            if (entry != null) {
                entry.close();
            }
        }
    }

}
